<template>
<div class="login">
  <el-form :model="ruleForm" status-icon :rules="rules" ref="login_form" label-width="100px" class="form">
    <img src="../assets/avatar.jpg" alt="头像" class="MugShot">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password" >
      <el-input v-model="ruleForm.password"></el-input>
    </el-form-item>
    <el-form-item>
    <el-button type="primary" @click="submitForm" class="loginBtn">登录</el-button>
    <el-button @click="resetForm">重置</el-button>
  </el-form-item>
  </el-form>
</div>
</template>

<script>
export default {
  data () {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    submitForm () {
      // console.log(this.$refs)
      this.$refs['login_form'].validate(isPass => {
        if (!isPass) return
        // console.log(isPass, this.$refs.login_form)
        this.$axios({
          url: 'login',
          method: 'post',
          data: this.ruleForm
        }).then(res => {
          // console.log(res)
          // localStorage.setItem('token', )
          const { meta, data } = res
          if (meta.status === 200) {
            localStorage.setItem('token', data.token)
            this.$message({
              message: '登录成功',
              type: 'success',
              showClose: true
            })
            this.$router.push('/index')
          } else {
            console.log(meta.msg)
            this.$message({
              message: meta.msg,
              type: 'error',
              showClose: true
            })
          }
        })
      })
    },
    resetForm () {
      this.$refs['login_form'].resetFields()
    }
  }
}
</script>

<style lang="scss">
  .login{
    height: 100%;
    background-color: #2d434c;
    overflow: hidden;
    .form{
      width: 30%;
      padding: 20px;
      padding-top: 70px;
      border-radius: 20px;
      background-color: white;
      margin: 0 auto;
      margin-top: 200px;
      position: relative;
      .MugShot{
        width: 20%;
        border: 5px solid white;
        border-radius: 50%;
        position: absolute;
        left: 50%;
        transform: translate(-50%,-110%)
      }
      .loginBtn {
        margin-right: 70px;
      }
    }
  }
</style>
